<template>
  <div class="app-container">
    <!--头部搜索工作栏-->
    <div class="header-search">
      <div class="header-left">
        <span class="fold-span" :style="{ borderColor: foldPanelShow ? '#2a67f4' : '#e3e5e8' }"
          @click="foldTreeEvent()">
          <svg-icon :icon-class="foldPanelShow ? 'process-all' : 'process-all-hide'"
            class="svg-icon-size-one svg-icon-margin-one"></svg-icon>
        </span>
      </div>
      <div class="header-right">
        <!-- 搜索工作栏 -->
        <el-form :model="searchParams" ref="queryForm" size="small" :inline="true"
          label-width="68px">
          <el-form-item label="事项主题" prop="title">
            <el-input v-model="searchParams.title" placeholder="请输入事项主题" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="事项状态" prop="status">
            <el-select v-model="searchParams.status" placeholder="请选择事项状态" clearable>
              <el-option v-for="(val, key) of itemStatusMap" :key="key" :value="key" :label="val">{{
                val }}</el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
            <el-button type="primary" plain icon="el-icon-plus" size="small"
              @click="handleAdd">新建事项</el-button>
            <el-button type="info" plain icon="" size="small" @click="batchRemove">批量移动</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <!--内容工作栏-->
    <div class="main-content">
      <div class="left-tree" v-show="foldPanelShow">
        <span class="form-group-title">
          <span>责任处室</span>
        </span>

        <el-scrollbar style="min-height: 300px; max-height: 500px; margin-bottom: 100px">
          <div class="items_div" v-for="(item, index) in officeData" :key="item.id" :class="activeIndex == index ? 'current_clicked' : 'current_noclick'
            " @click="operateRow(item, index)">
            <!-- <i
              class="el-icon-tickets"
              style=""
              :style="{
                'font-size': '24px',
                'margin-right': '8px',
              }"
            ></i> -->
            <span class="content_span">{{ item.officName }}</span>
            <span class="delete_btn">
              <el-button type="text" size="small" @click="editOffice(item)">编辑</el-button>
              <el-button type="text" size="small" @click="deleteOffice(item.id)">删除</el-button>
            </span>
          </div>
        </el-scrollbar>
        <div class="create-root-name" @click="createRootGroup">
          <svg-icon icon-class="process-add-name" class="svg-icon-size-two" />
          <span>新建处室</span>
        </div>
      </div>
      <div class="right-table">
        <el-table v-loading="table.loading" :data="table.data"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" />
          <el-table-column type="index" label="序号" align="center" width="50" />
          <el-table-column label="事项主题" prop="title" min-width="200" />
          <el-table-column label="事项类型" prop="type" min-width="120" align="center">
            <template v-slot="{ row }">
              <span>{{ userTypeMap[row.type] || row.type }}</span>
            </template>
          </el-table-column>
          <el-table-column label="开始日期" align="center" prop="startTime" width="160">
            <template v-slot="{ row }">
              <span>{{ parseTime(row.startTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="结束日期" align="center" prop="endTime" width="160">
            <template v-slot="{ row }">
              <span>{{ parseTime(row.endTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="事项状态" align="center" prop="status">
            <template v-slot="{ row }">
              <el-tag :type="getStatusType(row.status)" effect="plain">
                {{ itemStatusMap[row.status] || row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="160"
            class-name="small-padding fixed-width">
            <template v-slot="{ row }">
              <el-button v-if="row.status == 1" type="text" size="small"
                @click="publish(row)">发布</el-button>
              <el-button v-if="row.status == 2" size="small" type="text"
                @click="cancel(row)">撤销</el-button>
              <el-button :disabled="row.status != 1" type="text" size="small"
                @click="handleAdd(row)">编辑</el-button>
              <el-button type="text" size="small" @click="view(row)">详情</el-button>
              <el-button type="text" size="small" @click="remove(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 列表 -->

    <!-- 分页组件 -->
    <pagination v-show="table.total > 0" :total="table.total" :page.sync="table.page.pageNo"
      :limit.sync="table.page.pageSize" @pagination="getList" />
    <!--新建表单分组对话框-->
    <el-dialog :title="groupOperate.title" :visible.sync="groupOperate.showDialog" width="500px"
      center>
      <el-form ref="group" :model="groupOperate.form" :rules="groupOperate.rules"
        label-width="110px">
        <el-form-item label="处室名称：" prop="officName">
          <el-input v-model="groupOperate.form.officName" clearable />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelGroup" type="info" plain>取 消</el-button>
        <el-button type="primary" @click="submitGroup">确 定</el-button>
      </div>
    </el-dialog>
    <!--批量移动对话框-->
    <el-dialog title="移动至" :visible.sync="operateBtn.removeDialog" width="500px" append-to-body
      center>
      <div class="batch-remove-content">
        <span> 将选中的事项移动至： </span>
        <el-select v-model="operateBtn.officId" placeholder="请选择处室" clearable filterable>
          <el-option v-for="item in officeData" :key="item.id" :label="item.officName"
            :value="item.id">
          </el-option>
        </el-select>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelRemove" type="info" plain>取 消</el-button>
        <el-button type="primary" @click="submitRemove">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import { DICT_TYPE, getDictDatas } from "@/utils/dict";
import {
  getEnterpriseList,
  deleteEnterpriseInfo,
  updateEnterpriseInfo,
  getOfficeQueryPage,
  addOffice,
  deleteOffice,
  editOffice,
  batchEditByOfficeId,
} from "@/api/enterprise/info";

export default {
  name: 'corporate-items',
  data() {
    return {
      currentOfficeId: undefined, //当前选中的处室id
      activeIndex: 0,
      foldPanelShow: true,
      filterText: undefined,
      searchParams: {
        title: "",
        status: "",
      },
      // 事项状态选项
      itemStatusMap: {
        1: "待发布",
        2: "发布中",
        3: "已发布",
        // 4: "已删除",
      },
      userTypeMap: {
        1: "企业",
        2: "个人",
        3: '工作台'
      },
      table: {
        data: [],
        loading: false,
        total: 0,
        page: {
          pageNo: 1,
          pageSize: 10,
        },
      },
      officeData: [],
      groupOperate: {
        title: "新增处室",
        showDialog: false,
        form: {
          officName: undefined,
          id: undefined,
        },
        rules: {
          officName: [
            { required: true, message: "名称不能为空", trigger: "blur" },
          ],
        },
      },
      operateBtn: {
        selected: [],
        officId: undefined,
        removeDialog: false,
      },
    };
  },
  watch: {
    $route(to, from) {
      if (from.path == '/corporate/create') {
        this.getList();
      }
    }
  },
  async created() {
    await this.getOfficeQueryPage(); //获取处室的所有数据
  },
  methods: {
    handleSelectionChange(val) {
      this.operateBtn.selected = val;
    },
    operateRow(row, index) {
      this.activeIndex = index;
      this.currentOfficeId = row.id;
      this.getList();
    },
    getOfficeQueryPage() {
      getOfficeQueryPage({
        pageNo: 1,
        pageSize: 100,
      }).then((res) => {
        const { list } = res.data;
        this.officeData = list || [];
        this.currentOfficeId = list.length > 0 ? list[0].id : undefined;
        this.activeIndex = list.length > 0 ? 0 : undefined;
        this.handleQuery();
      });
    },
    createRootGroup() {
      this.groupOperate.showDialog = true;
      this.groupOperate.title = "新增处室";
      this.groupOperate.form.id = undefined;
    },
    editOffice(param) {
      this.groupOperate.showDialog = true;
      this.groupOperate.title = "编辑处室";
      this.groupOperate.form.officName = param.officName;
      this.groupOperate.form.id = param.id;
    },
    submitGroup() {
      this.$refs["group"].validate((valid) => {
        if (!valid) {
          return;
        }
        const ajaxMethod = this.groupOperate.form.id ? editOffice : addOffice;
        ajaxMethod({
          officName: this.groupOperate.form.officName,
          id: this.groupOperate.form.id,
        }).then((res) => {
          let message = this.groupOperate.form.id ? "新建成功！" : "编辑成功！";
          this.$message.success(message);
          this.cancelGroup();
        });
      });
    },
    cancelGroup() {
      this.groupOperate.showDialog = false;
      this.groupOperate.form = {
        officName: undefined,
        id: undefined,
      };
      this.getOfficeQueryPage();
      this.$refs["group"].resetFields();
    },
    deleteOffice(id) {
      deleteOffice([id]).then((res) => {
        this.$message.success("删除成功！");
        this.getOfficeQueryPage();
      });
    },
    foldTreeEvent() {
      this.foldPanelShow = !this.foldPanelShow;
    },
    handleQuery() {
      this.table.page.pageNo = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    getList() {
      this.table.loading = true;
      // 执行查询
      getEnterpriseList({
        officeId: this.currentOfficeId,
        ...this.searchParams,
        ...this.table.page,
      })
        .then((res) => {
          const { list, total } = res?.data || {};
          this.table.data = list || [];
          this.table.total = total || 0;
        })
        .finally(() => {
          this.table.loading = false;
        });
    },
    handleAdd(row) {
      let { id, officeId } = row;
      let officId = officeId == undefined ? this.currentOfficeId : officeId;
      this.$router.push({
        path: "/corporate/create",
        query: { id, officeId: officId },
      });
    },
    //批量移动
    batchRemove() {
      if (this.operateBtn.selected.length < 1) {
        this.$modal.msgWarning("请选择要批量移动的事项！");
        return;
      }
      this.operateBtn.removeDialog = true;
    },
    //批量移动确定操作
    submitRemove() {
      if (this.operateBtn.officId == undefined) {
        this.$message.warning("处室必填");
        return;
      }
      let params = {};
      params.officId = this.operateBtn.officId;
      let Index = this.officeData.findIndex(
        (item) => item.id == params.officId
      );
      params.enterpriseNoticeIds = this.operateBtn.selected.map(
        (item) => item.id
      );
      batchEditByOfficeId(params).then((res) => {
        this.$message.success("移动成功");
        this.currentOfficeId = params.officId;
        this.activeIndex = Index;
        this.table.page.pageNo = 1;
        this.table.page.pageSize = 10;
        this.cancelRemove();
      });
    },
    cancelRemove() {
      this.operateBtn.removeDialog = false;
      this.operateBtn.officId = undefined;
      this.operateBtn.selected = [];
      this.getList();
    },
    getStatusType(status) {
      return (
        {
          1: "info",
          2: "warning",
          3: "success",
          // 4: "danger",
        }[status] || "info"
      );
    },
    publish({ id }) {
      this.$confirm("确认发布事项通知", "发布事项", {
        type: "info",
      })
        .then(() => {
          return updateEnterpriseInfo({ id, status: "2" });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("发布成功");
        });
    },
    cancel({ id }) {
      this.$confirm("目前未到设定的截止日期，是否提前结束？", "撤销事项", {
        type: "warning",
      })
        .then(() => {
          return updateEnterpriseInfo({ id, status: "1" });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("撤销成功");
        });
    },
    view({ id }) {
      this.$router.push({
        path: "/corporate/detail",
        query: { id },
      });
    },
    remove({ id }) {
      this.$confirm("该操作不可恢复，是否删除该事项？", "删除事项", {
        type: "warning",
      })
        .then(() => {
          return deleteEnterpriseInfo(id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.header-search {
  // height: 56px;
  display: flex;

  // align-items: center;
  .header-left {
    // width: 20%;
    margin-right: 20px;

    .fold-span {
      display: inline-block;
      width: 32px;
      height: 32px;
      border-radius: 2px;
      border: 4px solid #2a67f4;
      cursor: pointer;
    }
  }

  .header-right {
    flex: 1;
    text-align: right;
  }
}

.main-content {
  min-height: 440px;
  display: flex;
  border: 1px solid #e8eaed;
}

.left-tree {
  position: relative;
  width: 300px;
  padding: 0 8px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  border-right: 1px solid #e8eaed;
}

.form-group-title {
  width: 100%;
  height: 40px;
  line-height: 40px;
  padding: 0 8px;
  position: relative;

  &:nth-child(1) {
    font-size: 16px;
    font-family: Source Han Sans CN-Medium, Source Han Sans CN;
    font-weight: 600;
    color: #23272e;
    border-bottom: 1px solid #e8eaed;
    margin-bottom: 5px;
  }

  .process-sort-icon {
    font-size: 20px;
    position: absolute;
    right: 0;
    top: 9px;
  }
}

.items_div {
  display: flex;
  height: 40px;
  align-items: center;
  font-size: 14px;
  color: #333;
  padding: 0 6px;

  .content_span {
    flex: 1;
    cursor: pointer;

    &:hover {
      color: #4497f7;
    }
  }

  .delete_btn {
    width: 80px;
    font-size: 14px;
    text-align: right;
    cursor: pointer;
    display: flex;
    justify-content: space-around;

    button:nth-child(2) {
      color: red;
    }
  }
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;

  .el-icon-plus:before {
    color: #bfc5cd;
  }

  .el-icon-delete:before {
    color: #bfc5cd;
  }

  .el-icon-edit:before {
    color: #bfc5cd;
  }

  .mouseover-span {
    display: inline-block;
    text-align: end;
    padding-right: 12px;
    padding-left: 20px;
  }
}

.create-root-name {
  position: absolute;
  bottom: 12px;
  height: 42px;
  line-height: 42px;
  text-align: center;
  width: 93%;
  background: #f6f7f8;
  border-radius: 2px 2px 2px 2px;
  border: 1px solid #e3e5e8;
  cursor: pointer;

  :nth-child(2) {
    margin-left: 8px;
    font-size: 16px;
    font-weight: 500;
  }
}

.right-table {
  flex-grow: 1;
  width: 0;
}

.svg-icon-size-one {
  font-size: 16px;
}

.svg-icon-margin-one {
  margin-top: 4px;
  margin-left: 4px;
}

.svg-icon-size-two {
  font-size: 20px;
}

.svg-icon-size-three {
  font-size: 24px;
}

.svg-icon-margin {
  margin-right: 10px;
}

.current_clicked {
  background: rgba(50, 51, 53, 0.031);
  color: #4497f7;
  border-radius: 2px;
  /* .content_span {
    color: #23272e;
  } */
  /* .delete_btn {
    :nth-child(1) {
      color: #23272e;
    }
  } */
}

.current_noclick {
  background: #fff;
}
</style>
